package com.etc.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.etc.common.ServiceException;
import com.etc.pojo.Student;
import com.etc.service.IStudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("student")
public class StudentController {

    @Autowired
    IStudentService service;
    
    @RequestMapping("search.action")
    public String search(Student stu,Integer pageNo, Model model) {
        pageNo = pageNo == null ? 1 : pageNo;
        // 第几页，  每一页的size
        PageHelper.startPage(pageNo, 5);
        List<Student> slist = service.findByCondition(stu);
        System.out.println(slist);
        // 把集合封装成PageInfo
        PageInfo<Student> page = new PageInfo<>(slist);
        model.addAttribute("page", page);
        return "student/search";
    }
    
    @RequestMapping("delete.action")
    public String delete(Integer id) {
        
        
        try {
            service.deleteById(id);
        } catch (ServiceException e) {
            e.printStackTrace();
            return "redirect: /error.jsp";
        }
        
        return "student/search";
    }
    // http://localhost:8080/student/1/update.action   ==> id=1
    @RequestMapping("{id}/update.action")
    public String update_init(@PathVariable()Integer id, Model mod) {
        System.out.println("@@@@@@@@@@@@" + id);
        
        Student stu = service.findById(id);
        mod.addAttribute("stu", stu);
        return "student/update";
    }
    
    
    @RequestMapping("update.action")
    public String update_init(Student stu, Model mod) {
        
        try {
            Student stu2 = service.update(stu);
            mod.addAttribute("stu", stu2);
            mod.addAttribute("msg", "succes");
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            mod.addAttribute("msg", e.getMessage());
            return "student/update";
        }
        
        return "student/update";
    }
}
